﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

using AzureGames.Data;
using AzureGames.Domain.Models;
using AzureGames.Domain.Contracts;
using System.IO;

namespace AzureGames.Domain.Handlers
{
    public class UpdateGame
    {
        private readonly IGameDefinitionRepository _gameDefinitionRepository;
        private readonly IAIPlayerRepository _gameAIRepository;


        public UpdateGame(IGameDefinitionRepository gameDefinitionRepository, IAIPlayerRepository gameAIRepository)
        {
            _gameDefinitionRepository = gameDefinitionRepository;
            _gameAIRepository = gameAIRepository;
        }

        public virtual void Execute(int gameId, HttpPostedFileBase scriptFile)
        {
            try
            {
                var existing = _gameDefinitionRepository.GetGameDefinitions().Where(n => n.ID == gameId);

                if (existing != null)
                {
                    if (scriptFile != null)
                    {
                        //Model.AIScript aiScript = GetAIScript(gameId,scriptFile);
                        //_gameAIRepository.Create(gameId, aiScript);

                        //CCTODO - update game with new aiscript which has been added
                    }
                }
            }

            catch (InvalidOperationException e)
            {
                throw new BusinessServicesException("Problem when trying to update game.", e);
            }
            
        }

        private Model.AIScript GetAIScript(int gameId, HttpPostedFileBase scriptFile)
        {
            var stream = scriptFile.InputStream;
            var contentType = scriptFile.ContentType;

            stream.Position = 0;

            // Now read s into a byte buffer.
            byte[] bytes = new byte[stream.Length];
            int numBytesToRead = (int)stream.Length;
            int numBytesRead = 0;
            while (numBytesToRead > 0)
            {
                // Read may return anything from 0 to 10.
                int n = stream.Read(bytes, numBytesRead, 10);
                // The end of the file is reached.
                if (n == 0)
                {
                    break;
                }
                numBytesRead += n;
                numBytesToRead -= n;
            }
            stream.Close();
            return new Model.AIScript
            {
                Script = bytes, GameId = gameId, ContentType ="text/x-javascript",
                FileName = scriptFile.FileName,
                Name = scriptFile.FileName
            };
        }
    }
}